<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Project extends T3WD_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	 
	public function Project()
	{
		 parent::__construct();
		 $this->_only_authorized_personnel();	
		 $this->load->helper('form');
		 
		 $name_module = 'project';
		if($name_module!==$this->session->userdata('name_module')){
			$this->session->set_userdata('name_module', $name_module);
			$this->session->set_userdata('userSort', 0);
			$this->session->set_userdata('userDirection', 0);
			$this->session->set_userdata('userCount', 0);	
			$this->session->set_userdata('search', '');

		}
		
	}	 


///////////////////////////////metodos de modulo////////////////////////////////////////////////////////////////	

	public function index()
	{
		redirect('project/view');
	}

	public function view()
	{
		$this->data_view['_HEADER_TITLE'] = 'Proyectos';
		$this->data_view['_message_error'] = $this->session->flashdata('error');
		$this->data_view['_message_sucessfully'] = $this->session->flashdata('sucessfully');
		
		//inicializacion
		$this->load->library('pagination');
		$this->load->helper('sort');
		$this->load->helper('string');		
		$this->load->model('project_model');
		
		//variables del buscador	
		if ($this->input->post('search_post')){
			
		$search = $this->input->post('search');				
			$this->session->set_userdata('search', $search);
		} 		

		$this->data_view['search_value'] = $this->session->userdata('search');			
		
		$post_search = $this->input->post('search');
		$search_post = $this->input->post('search_post');
		$session_search = $this->session->userdata('search');


		//variables del ordenador
		$sort = $this->session->userdata('userSort');
		$direction = $this->session->userdata('userDirection');
		$perPage = $this->session->userdata('userCount');		

		if(!$perPage)
		{
			$perPage = 6;
			$this->session->set_userdata('userCount', $perPage);
		}			

		if(!$sort)
		{
			$sort = 'id_proyecto';
			$this->session->set_userdata('userSort', $sort);
		}

		if(!$direction)
		{
			$direction = 'desc';
			$this->session->set_userdata('userDirection', $direction);
		}


		$this->data_view['sort'] = $sort;
		$this->data_view['direction'] = $direction;
		$this->data_view['perPage'] = $perPage;				

		//configuracion del paginador
		$config['base_url'] = base_url().index_page().'/project/view/pagina';
		$config['total_rows'] = $this->project_model->getNumProjects();
		$config['per_page'] = $perPage;	
		$config['uri_segment'] = 4;	
		
		$config['num_links'] = 1;
		$config['next_link'] = '<div class="page-right"></div>';
		$config['last_link'] = '<div class="page-far-right"></div>';
		$config['prev_link'] = '<div class="page-left"></div>';
		$config['first_link'] = '<div class="page-far-left"></div>';
		$config['num_tag_open'] = '<div id="page-info">';
		$config['num_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<div id="page-info"><strong>';
		$config['cur_tag_close'] = '</strong></div>';		
		
		$this->pagination->initialize($config);		

		$this->data_view['users'] = $this->project_model->getAllProjects($sort, $direction, $perPage, $this->uri->segment(4));	

		$this->data_view['pagination'] = $this->pagination->create_links();
		$this->data_view['pagina'] = $this->uri->segment(4);
		$this->data_view['numberPagina'] = $this->uri->segment(4) + 1;

		
		$this->load->view('project', $this->data_view);
	}
	
	
		public function sort()
	{
		if($this->input->post('sort'))	{
			$sort = $this->input->post('sort');
			$this->session->set_userdata('userSort', $sort);
		}		

		if($this->input->post('direction'))	{
			$direction = $this->input->post('direction');
			$this->session->set_userdata('userDirection', $direction);
		}
		
		redirect('project/view');
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		public function add()
	{
		//inicializacion
		$this->data_view['_HEADER_TITLE'] = 'Proyectos';
		$this->load->model('project_model');
		$this->load->helper('url');
		$this->load->library('form_validation');
		
		//redirecciono en caso de cancelar
		$cancel = $this->input->post('cancel');
		if (!empty($cancel))
			redirect('project/view');		

		//valido el formulario
		$this->form_validation->set_rules('nombre_proyecto', 'Nombre del proyecto', 'trim|required|min_length[1]|max_length[120]|xss_clean|callback__validation_unique_name');		
		$this->form_validation->set_rules('customer', 'Cliente', 'trim');
		$this->form_validation->set_rules('status', 'Estatus', 'trim');
		$this->form_validation->set_rules('staff', 'Lider del proyecto', 'trim');
		
		$this->form_validation->set_error_delimiters('<div class="error-left"></div>
			<div class="error-inner">', '</div>');

		if ($this->form_validation->run() == TRUE)
		{
			//traigo los datos
			$nombre_proyecto = $this->input->post('nombre_proyecto');
		    $customer = $this->input->post('customer');
			$status = $this->input->post('status');
			$staff = $this->input->post('staff');
			
			//realizo la insercion
			$id_project = $this->project_model->set_row_project($nombre_proyecto,$customer,$status);
			$id_project_staff = $this->project_model->add_staff_to_project($id_project,$staff, 'lider');
			
			//redirecciono
			if ($id_project) {
				$this->session->set_flashdata('sucessfully', 'Proyecto '.$nombre_proyecto.' creado satisfactoriamente');
				redirect('project/asign/'.$id_project);
			} else { 
				$this->session->set_flashdata('error', 'Error. No se pudo crear el Proyecto '.$nombre_proyecto);
				redirect('project/view');
			}
			
			
		}
		else
		{
			//busco los datos del cliente
			$this->load->model('customer_model');
			$this->data_view['array_customer'] = $this->customer_model->get_array_customer();
			$this->data_view['array_asign_project_select'] = $this->project_model->get_asign_select_project_default();
			$this->load->view('addProject', $this->data_view);
		}
		
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		public function update()
	{
		//inicializacion
		$this->data_view['_HEADER_TITLE'] = 'Proyectos';
		$this->load->model('project_model');
		$this->load->helper('url');
		$this->load->library('form_validation');
		
		
		//redirecciono en caso de cancelar
		$cancel = $this->input->post('cancel');
		if (!empty($cancel))
			redirect('project/view');
		
		//obtengo el id de usuario
		$id_project = ($this->input->post('id_project'))?$this->input->post('id_project'):$this->uri->segment(3);
		
		//valido el formulario
		$this->form_validation->set_rules('nombre_proyecto', 'Nombre del proyecto', 'trim|required|min_length[1]|max_length[120]|xss_clean');		
		$this->form_validation->set_rules('customer', 'Cliente', 'trim');
		$this->form_validation->set_rules('status', 'Estatus', 'trim');
		
		$this->form_validation->set_error_delimiters('<div class="error-left"></div>
			<div class="error-inner">', '</div>');

		if ($this->form_validation->run() == TRUE)
		{
			//traigo los datos
			$nombre = $this->input->post('nombre_proyecto');
		    $cliente = $this->input->post('customer');
			$status = $this->input->post('status');			
			
			//realizo la actualizacion
			$updated = $this->project_model->set_nombre($id_project,$nombre);
			$updated = $this->project_model->set_cliente($id_project,$cliente);
			$updated = $this->project_model->set_status($id_project,$status);
			
	
			//redirecciono
			if ($updated)
				$this->session->set_flashdata('sucessfully', 'Proyecto '.$nombre.' actualizado satisfactoriamente');
			else 
				$this->session->set_flashdata('error', 'Error. No se pudo actualizar el Proyecto '.$nombre);
			
			redirect('project/view');
			
		}
		else
		{
			//busco los datos asociados			
			$arrayUsuario = $this->project_model->get_row_project($id_project);
			
			$this->data_view['id_project'] = $id_project;	
			$this->data_view['nombre'] = $arrayUsuario['nombre_proyecto'];
			$this->data_view['customer'] = $arrayUsuario['id_cliente'];
			$this->data_view['status'] = $arrayUsuario['status_proyecto'];
			
			
			$this->load->model('customer_model');
			$this->data_view['array_customer'] = $this->customer_model->get_array_customer();	
						
			$this->load->view('updateProject', $this->data_view);
		}
		
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	public function delete(){
				
		$this->load->model('project_model');
		$deleted = $this->project_model->delete_project($this->uri->segment(3));
		
		//redirecciono
		if ($deleted)
			$this->session->set_flashdata('sucessfully', 'Proyecto eliminado');
		else 
			$this->session->set_flashdata('error', 'Error. No se pudo eliminar el proyecto');
		
		$url_paginador = ($this->uri->segment(4)=='pagina')?'/pagina/'.$this->uri->segment(5):'';
		redirect('project/view'.$url_paginador);		
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	


	public function asign()
	{
		$this->data_view['_HEADER_TITLE'] = 'Proyectos';
		$this->data_view['_message_error'] = $this->session->flashdata('error');
		$this->data_view['_message_sucessfully'] = $this->session->flashdata('sucessfully');
		
		//inicializacion		
		$this->load->model('project_model');
		
		//obtengo el id de usuario
		$id_project = $this->uri->segment(3);
		$this->data_view['id_project'] = $id_project;
		
		//consulta de usuarios
		$this->data_view['array_asign_project'] = $this->project_model->get_asign_list_project($id_project);
		$this->data_view['array_asign_project_select'] = $this->project_model->get_asign_select_project($id_project);
		$this->data_view['name_project'] = $this->project_model->get_nombre($id_project);
		
		/*$laca = $this->project_model->get_asign_select_project($id_project);
		print_r($laca);
		exit();*/

		
		$this->load->view('asignProject', $this->data_view);
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	


	public function asign_add()
	{
		$this->load->model('project_model');
		$id_project = $this->input->post('id_project');
		$id_staff = $this->input->post('staff');
		
		$type_user = $this->project_model->get_exists_lider_staff_project($id_project);
		$add = $this->project_model->add_staff_to_project($id_project,$id_staff,$type_user);
		
		//redirecciono
		if ($add)
			$this->session->set_flashdata('sucessfully', 'Usuario agregado al proyecto satisfactoriamente');
		else 
			$this->session->set_flashdata('error', 'Error. No se pudo adicionar el usuario al proyecto');
				
		redirect('project/asign/'.$id_project);	
	}	
	
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	


	public function asign_update()
	{
		$this->load->model('project_model');
		$id_project =  $this->uri->segment(3);
		$id_staff =  $this->uri->segment(4);
		
		$add = $this->project_model->set_type_user_project($id_project,$id_staff);		
		
		//redirecciono
		if ($add)
			$this->session->set_flashdata('sucessfully', 'Usuario seleccionado como lider del proyecto satisfactoriamente');
		else 
			$this->session->set_flashdata('error', 'Error. No se pudo realizar el cambio de rol');
				
		redirect('project/asign/'.$id_project);	
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	


	public function asign_delete()
	{
		$this->load->model('project_model');
		$id_project =  $this->uri->segment(3);
		$id_staff =  $this->uri->segment(4);
		
		$add = $this->project_model->delete_staff_project($id_staff);		
		
		//redirecciono
		if ($add)
			$this->session->set_flashdata('sucessfully', 'Usuario eliminado del proyecto satisfactoriamente');
		else 
			$this->session->set_flashdata('error', 'Error. No se pudo eliminar al usuario del proyecto');
				
		redirect('project/asign/'.$id_project);	
	}	
	
/////////////////////funciones auxiliares///////////////////////////////////////////////////////////////////////////////

	// funcion de validacion de no existencia de usuario
	function _validation_unique_name($str)
	{
		$id_project = $this->project_model->get_id_proyecto_by_nombre_proyecto($str);
		
		if ($id_project){
			$this->form_validation->set_message('_validation_unique_name', 'El Proyecto <strong>'.$str.'</strong> ya existe en la base de datos');
			return FALSE;
		} else	{
			return TRUE;
		}
	}
	
	
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/project.php */